package com.itheima.design.mode.strategy.orderHandle;

import com.itheima.design.mode.strategy.annotation.HandlerPromotionType;
import com.itheima.design.mode.strategy.service.PromotionCalculation;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 策略核心功能,获取所有策略注解的类型
 * 并将对应的class初始化到HandlerPromotionContext中
 */
@Component
public class HandlerPromotionProcessor implements ApplicationContextAware {

    /**
     * 获取所有的策略Beanclass加入HandlerPromotionContext属性中
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取所有策略注解的Bean
        Map<String, Object> PromotionStrategyMap = applicationContext.getBeansWithAnnotation(HandlerPromotionType.class);
        PromotionStrategyMap.forEach((k,v) ->{
            Class<PromotionCalculation> promotionCalculationClass = (Class<PromotionCalculation>)v.getClass();
            String type = promotionCalculationClass.getAnnotation(HandlerPromotionType.class).value();
            //将class加入map中,type作为key
            HandlerPromotionContext.promotionCalculationBeanMap.put(type,promotionCalculationClass);
        });
    }
}
